<template>
  <j-modal :title="title + $t('套餐')" :width="width" :visible="visible" switchFullscreen @cancel="handleCancel">
    <template slot="footer">
      <a-button @click="handleCancel" :disabled="confirmLoading">{{ $t('取消') }}</a-button>
      <a-button @click="handleOk" type="primary" :disabled="confirmLoading">{{ $t('保存') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div :disabled="formDisabled">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="24">
              <a-form-model-item :label="$t('团购ID')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dealId">
                <a-input v-model="model.dealId" :placeholder="$t('请输入团购ID')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('商品名称')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" :placeholder="$t('请输入商品名称')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('包含卖品')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-row>
                  <span style="color: #f2944b">{{
                  $t('1、该套餐中所包含的商品信息应该与抖音平台上架的此商品中的内容保持一致')
                }}</span>
                </a-row>
                <a-row>
                  <span style="color: #f2944b">{{
                  $t('2、若本次核销需要出实体游戏币，需要添加并选择“')
                }}</span>
                 <span style="color: #f2944b;font-weight: bold;">{{
                  $t('游戏币')
                }}</span>
                 <span style="color: #f2944b">{{
                  $t('”形态的商品')
                }}</span>
                </a-row>
                <a-row>
                  <span style="color: #f2944b">{{
                  $t('3、若本次核销币值需要存卡，需要添加并选择“')
                }}</span>
                 <span style="color: #f2944b;font-weight: bold;">{{
                  $t('会员充币')
                }}</span>
                 <span style="color: #f2944b">{{
                  $t('”形态的商品')
                }}</span>
                </a-row>
                <a-table :columns="columns" :dataSource="dataSource" bordered class="customTable" :pagination="false">
                  <template slot="action" slot-scope="text, record">
                    <a-icon type="close" @click="deleteGoods(text, record)" />
                  </template>
                  <template slot="select" slot-scope="text, record, index">
                    <a-select
                      v-model="record.goodsForm"
                      show-search
                      :placeholder="$t('请选择')"
                      :filter-option="false"
                      :not-found-content="null"
                      @change="(value) => handleFormChange(value, index)"
                    >
                      <a-select-option v-for="good in addFormList" :key="good.value">{{ good.title }}</a-select-option>
                    </a-select>
                  </template>
                  <template slot="selectTwo" slot-scope="text, record">
                    <a-select
                      v-model="record.goodsId"
                      show-search
                      :placeholder="$t('请输入商品编码/名称')"
                      :filter-option="false"
                      :not-found-content="null"
                      @search="(val)=>handleGoodsSearch(record.goodsForm, val)"
                    >
                      <a-select-option v-for="good in addGoodsList" :key="good.id">{{ good.name }}</a-select-option>
                    </a-select>
                  </template>
                  <template slot="inputNum" slot-scope="text, record">
                    <a-input-number v-model="record.amount"

                                    :formatter="formatter"
                                  :parser="parser"
                                    style="width: 100%;"
                    ></a-input-number>
                  </template>
                  <template slot="isGift" slot-scope="text, record">
                    <a-checkbox v-model="record.isGiftState" @change="clickIsGift"></a-checkbox>
                  </template>
                </a-table>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, httpAction, downFile, UploadFile } from '@/api/manage'
import {formatter, parser} from "@api/comm";
let _self
export default {
  name: 'TiktokGoodsModal',
  components: {},
  data() {
    return {
      formatter,
      parser,
      title: '',
      width: 900,
      visible: false,
      disableSubmit: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      confirmLoading: false,
      validatorRules: {
        dealId: [{ required: true, message: this.$t('请输入团购ID') }],
        name: [{ required: true, message: this.$t('请输入商品名称') }],
      },
      url: {
        add: '/tiktok/bisTiktokGoods/add',
        edit: '/tiktok/bisTiktokGoods/edit',
        queryById: '/tiktok/bisTiktokGoods/queryById',
      },
      columns: [
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  _self.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('商品形态'),
          dataIndex: 'form',
          align: 'center',
          width: 180,
          scopedSlots: { customRender: 'select' },
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'name',
          align: 'center',
          width: 340,
          scopedSlots: { customRender: 'selectTwo' },
        },
        {
          title: this.$t('数量'),
          key: 'num',
          dataIndex: 'num',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'inputNum' },
        },
      ],
      dataSource: [],
      addFormList: [],
      addGoodsList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    _self = this
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.dataSource = []
      this.getFormList()
      if (record.id) {
        getAction('/tiktok/bisTiktokGoods/queryBisTiktokGoodsPackageByMainId', { id: record.id }).then((res) => {
          if (res.success) {
            this.dataSource = res.result
            let list = []
            this.dataSource.forEach((ds) => {
              let dtl = {
                id: ds.goodsId,
                name: ds.goodsId_dictText,
              }
              list.push(dtl)
            })
            this.addGoodsList = list
          }
        })
      } else {
        this.getGoodsList()
      }
    },
    handleOk() {
      const that = this
      let param = {}
      let i = 0
      that.dataSource.forEach((col) => {
        if (col.goodsForm == undefined) {
          this.$message.warning(this.$t('请选择商品形态'))
          return
        }
        if (col.goodsId == undefined) {
          this.$message.warning(this.$t('请选择商品名称'))
          return
        }
        if (col.amount == '') {
          this.$message.warning(this.$t('商品数量不能为空'))
          return
        }
        i++
      })
      // 触发表单验证
      if (i == this.dataSource.length) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            param = that.model
            param.bisTiktokGoodsPackageList = that.dataSource
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            httpAction(httpurl, param, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.close()
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      }
    },
    addGoods() {
      let obj = {
        goodsForm: undefined,
        goodsId: undefined,
        amount: 1,
      }
      this.dataSource.push(obj)
    },
    deleteGoods(a, b) {
      this.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = this.dataSource.indexOf(col)
          this.dataSource.splice(index, 1)
        }
      })
    },
    handleFormChange(value) {
      this.getGoodsList(value)
    },
    handleGoodsSearch(form, value) {
      this.getGoodsList(form, value)
    },
    getFormList() {
      let that = this
      that.addFormList = []
      initDictOptions('bis_goods_infor.form').then((res) => {
        if (res.success) {
          that.addFormList = res.result.filter(item=>{
            return item.value != '5' && item.value != '7' && item.value != '11' && item.value != '13' && item.value != '16'
          })
        }
      })
    },
    getGoodsList(form, value) {
      this.addGoodsList = []
      let querydata = {}
      querydata.pageIndex = 1
      querydata.pageSize = 10
      querydata.form = form
      querydata.goodsInfo = value
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          this.addGoodsList = res.result.records
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>